<?php

namespace Home\Controller;

use Think\Controller;

include "MyDesController.class.php";
//获取token的url
define('TOKEN_URL','http://120.27.24.3/interface/login');
//验证请求的url
define('CHECK_URL','http://120.27.24.3/interface/checkUser');
//账户名
define('SOURCENAME','huoyanshidai');
//密码
define('PASSWORD','lOGmUj6L7MIn');
define('TOKEN_CACHE' , 'tokens.txt');

class BlacklistController extends Controller
{
    /*
     * 获取前端传过来的用户名，身份证号，手机号并检测
     *
     */
    public function getData()
    {
        try {
            if (IS_POST) {
                $getJson = file_get_contents("php://input");
                $getArray = json_decode($getJson,true);
                $userid = $getArray['customer_id'];
                $name = $getArray['name'];
                $idcard = $getArray['idcard'];
                $phone = $getArray['phone'];
                $res = $this->check($name,$idcard,$phone);
                if ($res['black_result'] == 'Y') {
                    $database = $this->addDataBase($res);
                }
                $result['code'] = 0;
                $result['msg'] = "成功";
                $result['data'] = array("customer_id"=>$userid,"name"=>$name,"black_result"=>$res['black_result'],"risk_level"=>$res['risk_level']);
                echo json_encode($result);
            }
        } catch (BusinessException $e) {
            $this->ajaxReturn(['code' => $e->getCode(), 'msg' => $e->getMessage()]);
        }
    }
    /*外部访问接口*/
    public function  ckweizhen($name,$idCard,$phone){
        return $res=$this->check($name,$idCard,$phone);
    }
    /*
     * 命中黑名单则记录进数据库
     * @param Array $data 入库的数据
     */
    public function addDataBase($data)
//    protected function addDataBase($data)
    {
        $model = M("black_list");
        $arr = [
            "id_num"    =>  $data['idCard'],
            "reason"    =>  "融捷信黑名单",
            "code"      =>  "236",
            "add_time"  =>  time(),
            ];
            $select = $model->where("id_num = ".'"'.$data['idCard'].'"'." AND status = 1")->select();
        if ($select) {
            $model->where("id_num = ".$data['idCard'])->setField("add_time",time());
        } else {
            $res = $model->add($arr);
        }
        
    }

    /*
     * 检测
     * @param $name 姓名
     * @param $idCard 身份证号码
     * @param $phone 手机号
     * return $checkRes Array
     */
    protected function check($name,$idCard,$phone)
    {
        if (empty($name)) {
            echo json_encode(array("code"=>100,"msg"=>"姓名不可为空"));
            die;
        }
        if (empty($idCard)) {
            echo json_encode(array("code"=>100,"msg"=>"身份证号不可为空"));
            die;
        }
        if (empty($phone)) {
            echo json_encode(array("code"=>100,"msg"=>"手机号不可为空"));
            die;
        }
        $array = array();
        $array = ["name"=>$name,"idCard"=>$idCard,"phone"=>$phone];
        $json = json_encode($array);
        $key = $this->getToken();
        $des = new CryptDes($key,'huoyan');
        $desRes = $des->encrypt($json);
        //生成唯一标识，当前时间戳
        $transNo = time();
        $query = ["sourceName"=>SOURCENAME,"transNo"=>$transNo,"data"=>$desRes];
        $data = json_encode($query);
        $url = CHECK_URL;
        $resData = $this->post($url,$data);
        $arrData = json_decode($resData,true);
        if ($arrData['status'] == 200) {
            $checkRes = $des->decrypt($arrData['data']);
            return json_decode($checkRes,true);
        } else {
            return $arrData['desc'];
        }
    }

    /*
     * 获取token
     */
    protected function getToken()
    {
        //判断是否已经缓存
        if (file_exists(TOKEN_CACHE)) {
            $jsonData = file_get_contents(TOKEN_CACHE);
            $data = json_decode($jsonData , true);
            //判断是否过期
            if (filemtime(TOKEN_CACHE)+7200>time()) {
                return $data['data']['token'];
            }
            unlink(TOKEN_CACHE);
        }
        //账户和密码信息 JSON
        $arr = array('sourceName'=>SOURCENAME,'password'=>md5(PASSWORD));
        $PersonData = json_encode($arr);
        $token = $this->post(TOKEN_URL,$PersonData);
        //var_dump($token);
        $data = json_decode($token , true);
        //判断是否成功
        if ($data['status'] == 200)
        {
            file_put_contents(TOKEN_CACHE, $token);
            return $data['data']['token'];
        } else {
        	return "token获取失败,请联系工作人员解决！";
        }
    }

    /*
     * 通过CURL提供POST请求
     */
    protected function post($url,$data)
    {
        //初始化会话
		$ch = curl_init();
		//设置会话参数
		//设置URL
		curl_setopt($ch, CURLOPT_URL, $url);
		//是否返回原生数据，true:返回数据，false:直接输出
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		//是否显示请求头信息
		curl_setopt($ch, CURLOPT_HEADER, false);
		//主机认证：
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		//身份认证
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		//是否是POST请求
		curl_setopt($ch, CURLOPT_POST, true);
		//设置POST请求数据
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

		//执行会话
		$result = curl_exec($ch);
		//关闭会话
		curl_close($ch);

		return $result;
    }

}
